<template>
  <div>
    <div v-if="!sys.appId">
      <div class="showcovertoast">
        <div class="showcovertitle">微信小程序</div>
        <div class="wxlogoimg">
          <img class="el-upload-list__item-thumbnail" src="@/assets/img/wxlogo.png" alt="" />
        </div>
        <div class="footerbtn">
          <a href="https://mp.weixin.qq.com/cgi-bin/wx?token=&lang=zh_CN" target="_blank"
            style="color: var(--main-color); text-decoration: none">
            <el-button class="btnstyle" round> 立即注册 </el-button>
          </a>
          <el-button class="btnstyle" type="primary" round @click="getAuthorizerQrcode">
            立即授权
          </el-button>
        </div>
      </div>
      <div class="footer-size">
        <p class="footer-size-one" style="color: var(--main-color)">注意:小程序主体必须是企业(包含个体工商户)</p>
        <p class="footer-size-two">将小程序授权给本系统，系统将会自动帮您生成店铺小程序，并提交到微信官方微信审核，您不需要做复杂操作，即可管理您的小程序平台。</p>
      </div>
    </div>
    <div class="weapp-info" v-else>
      <div class="weapp-message">
        <el-form :model="sys" label-width="auto" style="margin-top: 20px">
          <el-form-item label="小程序名称：">
            <div class="iptbox" style="display: flex; align-items: center">
              <h3 style="">{{ sys.nickName }}</h3>
              <el-button style="margin-left: 10px" type="danger" size="small" plain round
                @click="handleDelete">解绑小程序</el-button>
              <el-button size="small" style="margin-left: 10px" round @click="redupAuthorizer">
                重新授权
              </el-button>
            </div>
          </el-form-item>
          <el-form-item label="小程序简称：">
            <div class="iptbox">
              <p>{{ sys.nickName }}</p>
            </div>
          </el-form-item>
          <el-form-item label="小程序头像：">
            <div class="iptbox">
              <img class="iptboximg" :src="sys.headImg" />
            </div>
          </el-form-item>
          <el-form-item label="小程序介绍：">
            <div class="iptbox">
              <p>{{ sys.signature }}</p>
            </div>
          </el-form-item>
          <el-form-item label="小程序AppID：">
            <div class="iptbox">
              <p>{{ sys.appId }}</p>
            </div>
          </el-form-item>
          <el-form-item label="服务类目：">
            <div class="iptbox">
              <p>{{ sys.categories }}</p>
            </div>
          </el-form-item>
          <el-form-item label="主体信息：">
            <div class="iptbox">
              <p>{{ sys.principalName }}</p>
            </div>
          </el-form-item>
          <el-form-item label="微信认证：">
            <div class="iptbox">
              <p style="color: var(--main-color)">{{
                sys.verifyType === -1 ? '未认证' : '已认证'
              }}</p>
            </div>
          </el-form-item>
          <el-form-item label="更新时间：">
            <span>{{ sys.versionUpdateTime }}</span>
          </el-form-item>
        </el-form>
      </div>
      <div class="webapp-code">
        <p>微信 “扫一扫” 访问线上小程序</p>
        <img :src="sys.qrcodeUrl" referrerpolicy="no-referrer" style="width: 140px; height: 140px; margin-top: 20px" />

        <div class="operation">
          <a>线上版本号：{{ sys.releaseVersion }}</a>
          <div class="line"></div>
          <a download :href="sys.qrcodeUrl">下载小程序码</a>
        </div>

        <div class="desc">下载更多尺寸的小程序码可以到“微信小程序后台-设置-基本设置-小程序码”</div>

        <el-form :model="sys" class="versionText">
          <el-form-item label="最新版本号：">
            <span style="font-size: 16px">{{ sys.version }}</span>
            <el-button size="small" class="btnstyle" round type="primary" @click="handleUpdateWeApp"
              v-if="sys.version !== sys.releaseVersion" :icon="Top">
              立即更新
            </el-button>
          </el-form-item>
          <el-form-item label="审核状态：">
            <div style="display: flex; align-items: center">
              <p v-if="auditStatus == 0" style="color: var(--main-color); font-size: 16px">审核通过</p>
              <p v-if="auditStatus == 1" style="color: #fd4e4e; font-size: 16px">审核失败</p>
              <p v-if="auditStatus == 2" style="color: var(--main-color); font-size: 16px">审核中</p>
              <el-button size="small" v-if="auditStatus == 2" class="btnstyle" round @click="handleUnbind">
                撤回审核
              </el-button>
            </div>

            <el-button size="small" v-if="auditStatus == 1" class="btnstyle" round @click="showReasonDialog = true">
              查看失败原因
            </el-button>
          </el-form-item>
        </el-form>

        <div class="btn-list">
          <div class="manage-btn" @click="getWeAppTrialQRCodeInfo(0)">查看体验码</div>
          <div class="set-btn" @click="goDecoration">去装修</div>
        </div>
      </div>
    </div>

    <el-dialog v-model="showWeappCodeDialog" width="260" title="查看体验码" :close-on-click-modal="false">
      <div style="text-align: center">
        <img :src="weappQrCode" style="width: 200px; height: 200px" />
      </div>
    </el-dialog>

    <el-dialog v-model="showReasonDialog" width="360" title="审核失败原因" :close-on-click-modal="false">
      <div v-html="auditFailReason"></div>
    </el-dialog>

    <el-dialog v-model="showUpdateDialog" title="小程序更新" width="460" @close="handleClose" :close-on-click-modal="false">
      <div v-loading="auditLoading">
        <el-form :model="sys">
          <el-form-item label="线上版本号：">
            <el-tag type="info">{{ sys.releaseVersion }}</el-tag>
          </el-form-item>
          <el-form-item label="最新版本号：">
            <el-tag type="primary">{{ sys.version }}</el-tag>
          </el-form-item>
          <el-form-item label="更新时间：">
            <el-tag type="info">{{ sys.versionUpdateTime }}</el-tag>
          </el-form-item>
          <el-form-item label="体验码：">
            <img :src="weappQrCode" style="width: 200px; height: 200px" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleAuditWeApp">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  delBindWeapp,
  getAuthQr,
  getWeAppAuditStatus,
  getWeAppTrialQRCode,
  getWXAuthorizerInfo,
  undoWeappAudit,
  weAppAudit,
  weAppUpdate
} from '@/api/ApiList'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Top } from '@element-plus/icons-vue'

const sys = reactive({
  nickName: '',
  headImg: '',
  signature: '',
  appId: '',
  categories: '',
  principalName: '',
  verifyType: -1,
  version: '',
  versionUpdateTime: '',
  releaseVersion: '',
  auditStatus: '',
  qrcodeUrl: ''
})

const router = useRouter()

const auditStatus = ref()
const weappQrCode = ref('')
const showWeappCodeDialog = ref(false)
const showUpdateDialog = ref(false)
const auditLoading = ref(false)
const auditFailReason = ref('')
const showReasonDialog = ref(false)

function redupAuthorizer() {
  ElMessageBox.confirm('确认或换绑其他小程序吗？', '重新授权小程序', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    getAuthorizerQrcode()
  })
}

async function getAuthorizerQrcode() {
  const res = await getAuthQr()
  if (res.code === '00000') {
    window.open(res.msg)
  }
}

async function getWeAppStatus() {
  const res = await getWeAppAuditStatus({})
  if (res.code === '00000') {
    auditStatus.value = res.data.status
    auditFailReason.value = res.data.reason
  }
}

async function handleUpdateWeApp() {
  let loadingMessage: ReturnType<typeof ElMessage> | null = null
  loadingMessage = ElMessage({
    message: '正在更新，请稍后...',
    type: 'info',
    duration: 0,
    showClose: false
  })
  try {
    const res = await weAppUpdate({})
    if (res.code === '00000') {
      ElMessage.success('更新版本成功')
      getWeAppTrialQRCodeInfo(1)
      getData()
      showUpdateDialog.value = true
    }
  } catch (e) {
  } finally {
    loadingMessage.close()
  }
}

async function handleAuditWeApp() {
  try {
    auditLoading.value = true
    const res = await weAppAudit({})
    if (res.code === '00000') {
      ElMessage.success('提交审核成功')
      showUpdateDialog.value = false
      await getData()
    }
  } catch (e) {
  } finally {
    auditLoading.value = false
  }
}

async function getWeAppTrialQRCodeInfo(showDialog: number) {
  const res = await getWeAppTrialQRCode({})
  if (res.code === '00000') {
    weappQrCode.value = res.msg
    if (showDialog === 0) {
      showWeappCodeDialog.value = true
    }
  }
}

function handleDelete() {
  ElMessageBox.confirm(
    '确定解绑该小程序吗？解绑后小程序将会删除全部数据，请谨慎操作！',
    '解绑小程序',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteWeappAuth()
  })
}

function handleClose() {
  showUpdateDialog.value = false
}

function goDecoration() {
  router.push('/decoration/driving_school_decoration/weapp_diy')
}

async function deleteWeappAuth() {
  const res = await delBindWeapp({})
  if (res) {
    ElMessage.success('解绑成功')
    await getData()
  }
}

function handleUnbind() {
  ElMessageBox.confirm('确定撤回小程序审核吗？', '撤回审核', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleUndoWeapp()
  })
}

async function handleUndoWeapp() {
  const res = await undoWeappAudit({})
  if (res) {
    ElMessage.success('撤回审核成功')
    await getData()
  }
}

async function getData() {
  const res = await getWXAuthorizerInfo({})
  if (res.code === '00000' && res.data) {
    sys.nickName = res.data.nickName
    sys.headImg = res.data.headImg
    sys.signature = res.data.signature
    sys.appId = res.data.appId
    sys.categories = res.data.categories
    sys.principalName = res.data.principalName
    sys.verifyType = res.data.verifyType
    sys.version = res.data.version
    sys.versionUpdateTime = res.data.versionUpdateTime
    sys.releaseVersion = res.data.releaseVersion
    sys.qrcodeUrl = res.data.qrcodeUrl

    await getWeAppStatus()
  } else {
    sys.appId = ''
    ElMessage.error(res.msg)
  }
}

onMounted(() => {
  getData()
})
</script>

<style scoped lang="scss">
.page-content {
  width: 100%;

  .svg-icon {
    width: 1.8em;
    height: 1.8em;
    overflow: hidden;
    vertical-align: -8px;
    fill: currentcolor;
  }
}

.tag-item+.tag-item {
  margin-left: 5px;
}

.label {
  float: left;
  margin: 0.5rem 0 0.5rem 1.5rem;
  display: inline;
}

.labellist .label:nth-child(1) {
  margin-left: 0;
}

.bankcont_title_text {
  float: left;
  margin-right: 1rem;
  font-weight: bold;
}

.label_sonli {
  color: #5d87ff;
}

.tag-item {
  margin-left: 5px;
}

.tagcontsize {
  color: #999;
}

.tagcontbigsize {
  margin-top: 0.5rem;
}

.cartcont {
  margin-top: 0.2rem;
}

.tableimg {
  width: 100%;
  height: 100%;
}

.title_box_left {
  float: left;
  width: 4rem;
  height: 4rem;
  border-radius: 0.5rem;
  overflow: hidden;
  margin-right: 1rem;
}

.title_box_right {
  float: right;
  float: left;
}

.bankcont_title_text {
  height: 2rem;
  margin-top: 0.3rem;
}

.columnvideo {
  border-radius: 0.5rem;
}

.wxlogoimg {
  width: 260px;
  height: 220px;
}

.wxlogoimg img {
  width: 100%;
}

.showcovertoast {
  width: 14%;
  height: 440px;
  border-radius: 20px;
  box-shadow: 0 5px 20px 0 rgba(11, 3, 6, 0.1);
  margin-left: 43%;
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 50px;
}

.footerbtn {
  width: 100%;
  display: flex;
  justify-content: center;
}

.btnstyle {
  margin-left: 20px;
}

.footerbtn .btnstyle:nth-child(1) {
  margin-left: 0px;
}

.showcovertitle {
  width: 100%;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin-top: 40px;
}

.footer-size {
  line-height: 32px;
  font-size: 14px;
}

.footer-size-one {
  display: block;
  width: 100%;
  text-align: center;
  margin-top: 40px;
}

.footer-size-two {
  display: block;
  width: 100%;
  text-align: center;
}

.iptbox {
  //width: 40%;
}

.iptbox .iptboxipt {
  //width: 70%;
}

.iptboximg {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.weapp-info {
  display: flex;
  margin-top: 30px;

  .webapp-code {
    width: 360px;
    border-radius: 12px;
    box-shadow: 0 5px 20px 0 rgba(11, 3, 6, 0.1);
    padding-top: 20px;

    display: flex;
    flex-direction: column;
    //justify-content: space-around;
    align-items: center;

    .operation {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 20px;
      font-size: 14px;

      a {
        text-decoration: none;
        color: var(--el-color-primary);
      }

      .line {
        width: 1px;
        height: 10px;
        background-color: var(--el-color-primary);
        margin: 0 15px;
      }
    }

    .desc {
      padding: 0 20px;
      margin-top: 20px;
      font-size: 12px;
      margin-bottom: 50px;
      color: #888;
    }

    .versionText {
      :deep(.el-form-item__label) {
        font-size: 16px;
      }
    }

    .btn-list {
      display: flex;
      width: 100%;
      justify-content: center;
      margin-top: 30px;
      margin-bottom: 20px;

      .manage-btn {
        width: 120px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 20px;
        border: 1px solid #ccc;
        margin-right: 15px;
        cursor: pointer;
      }

      .set-btn {
        width: 100px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 20px;
        color: #fff;
        background: var(--el-color-primary);
        cursor: pointer;
      }
    }
  }

  .weapp-message {
    width: 460px;
    border-radius: 12px;
    box-shadow: 0 5px 20px 0 rgba(11, 3, 6, 0.1);
    padding: 10px;
    margin-right: 20px;
  }
}
</style>
